import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.MemoryImageSource;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.image.codec.jpeg.JPEGEncodeParam;

public class JPGResizer extends Frame implements JPEGDecoder.PixelArray{
	private final int TARGET_WIDTH = 500;
	private final int TARGET_HEIGHT = 500;
	
	private int width;
	private int height;
	private int[] pix;
	private int[] target_pix = new int[TARGET_HEIGHT*TARGET_WIDTH];
	JPEGDecoder decoder = null;
	
	@Override
	public void setPixel(int x, int y, int argb) {
		pix[x+y*width] = argb;
	}

	@Override
	public void setSize(int width, int height) {
		this.width = width;
		this.height = height;
		pix = new int[width*height];
	}
	
	public static void main(String args[]){
		new JPGResizer("large.jpg");
	}
	
	public JPGResizer(String srcName){
		decoder = new JPEGDecoder();
		try{
			FileInputStream fis = new FileInputStream(srcName);
			decoder.decode(fis, this);
			algo1();
			MemoryImageSource mi = new MemoryImageSource(
										this.TARGET_WIDTH,
										this.TARGET_HEIGHT,
										this.target_pix,
										0,
										this.TARGET_WIDTH
										);
			Image im = createImage(mi);
			BufferedImage bi = new BufferedImage(this.TARGET_WIDTH,
										this.TARGET_HEIGHT, BufferedImage.TYPE_INT_RGB);
			Graphics2D biContext = bi.createGraphics();
			biContext.drawImage(im, 0, 0, null);
			FileOutputStream fos = new FileOutputStream("xx.jpg");
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
			JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(bi);
			jep.setQuality((float)0.75,true);
			encoder.encode(bi, jep);
			fos.flush();
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	//nearest interpolation
	public void algo1(){
		int srcX = 0;
		int srcY = 0;
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		BufferedWriter bw = null;
		try{
			bw = new BufferedWriter(new FileWriter(new File("temp.txt")));
		}catch(Exception e){
			e.printStackTrace();
		}
		for(int i=0; i<this.TARGET_HEIGHT; ++i){
			srcY = (int)(i*this.height/this.TARGET_HEIGHT);
			for(int j=0;j<this.TARGET_WIDTH; ++j){
				srcX = (int)(j*this.width/this.TARGET_WIDTH);
				target_pix[i*TARGET_WIDTH+j] = pix[srcX + srcY*width];
				try{
					bw.write("("+i*TARGET_WIDTH+","+j+")---->("+srcX+","+srcY*width+")\n");
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	
}
